<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '新增用户',
  },
  needLogin: true,
}
</route>

<template>
  <view class="add-user-container p-4">
    <wd-form ref="formRef" :model="formData" :rules="rules">
      <wd-form-item label="手机号" prop="phone">
        <wd-input v-model="formData.phone" placeholder="请输入手机号" />
      </wd-form-item>
      <wd-form-item label="用户描述" prop="username">
        <wd-input v-model="formData.username" placeholder="请输入用户描述" />
      </wd-form-item>
      <view class="mt-8">
        <wd-button type="primary" block @click="handleSubmit">提交</wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/store'
import { upsertCommunityUsersAPI } from '@/service/iam'

const userStore = useUserStore()
const formRef = ref()
const communityId = userStore.currentCommunity?.community.id

const formData = ref({
  phone: '',
  username: '',
  password: '',
})

const rules = {
  phone: [{ required: true, message: '请输入手机号' }],
  username: [{ required: true, message: '请输入用户名' }],
  password: [{ required: true, message: '请输入密码' }],
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    await upsertCommunityUsersAPI({
      communityId: communityId!,
      phone: formData.value.phone,
      description: formData.value.username,
      status: true,
      role: 'USER',
    })

    uni.showToast({
      title: '添加成功',
      icon: 'success',
    })

    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/community-users/index',
      })
    }, 1500)
  } catch (error) {
    uni.showToast({
      title: '添加失败',
      icon: 'error',
    })
  }
}
</script>

<style lang="scss" scoped>
.add-user-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 90vh;
  background-color: #fff;
}
</style>
